package ks.client.processor;

import org.w3c.dom.Node;

import ks.client.Initializer;
import ks.client.controllers.IconsController;
import ks.client.controllers.LobbyOutputController;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;
import ks.framework.interfaces.IClientProcessor;

/**
 * Client-side processor of messages received from Server.
 * <p>
 * This must be altered properly to be able to handle the wide variety
 * of requests being received from the server. This is a design 
 * issue that will be addressed at its proper time.
 * 
 * @author George Heineman
 */
public class Processor implements IClientProcessor {

	/** The core Processor knows about the Lobby for which it is in control. */
	Lobby lobby;

	/** 
	 * Each processor knows the lobby for which it is responsible.
	 * 
	 * @param lob
	 */
	public Processor (Lobby lob) {
		this.lobby = lob;
	}

	@Override
	public boolean process(Message m) {
		// retrieve output requests.
		if (m.getName().equalsIgnoreCase("output")) {
			return new LobbyOutputController(lobby).process(m);
		} 

// BEGIN-EXAMPLE
		if (m.getName().equalsIgnoreCase("icons")) {
			return new IconsController(lobby).process(m);
		}
// END-EXAMPLE
		
		// other request controllers would go here...
		
		// note that you will LIKELY need to deal specially with ACK and NACK 
		// requests because they refer to commands that have been sent to the server
		// which either succeeded (or failed) and you will need to know about this.
		
		// Therefore you will likely need some sort of registration scheme that keeps
		// track of commands sent (by their unique ID) and can match up against the 
		// received ACK and NACK. These details will become much clearer during Implementation
		// so don't worry about it right now for design.
		
		// this is here for debugging purposes. You will likely need
		// to have some means for reacting to nack events as necessary
		if (m.getName().equalsIgnoreCase("nack")) {
			Node output = m.contents();
			String s = "Nack Received:" + output.getTextContent();
			lobby.append(s);
			return true;
		} 

		// this is here for debugging purposes. You will likely need
		// to have some means for reacting to ack events as necessary
		if (m.getName().equalsIgnoreCase("ack")) {
			Node output = m.contents();
			String s = "Ack Received:" + output.getTextContent();
			lobby.append(s);
			return true;
		}
		
		return false;
	}

	/**
	 * Connection has been made. Tell lobby.
	 * 
	 * @param status
	 */
	public void connected(boolean status) {
		lobby.connected(status);
		
		Initializer.init(lobby);
	}
}
